import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:gameplay_flutter/lib_baseview/lib_baseview.dart';

import '../../../../lib_runtime/event_center.dart';
import '../../../../lib_runtime/event_constant.dart';
import '../../../../lib_runtime/logger.dart';
import '../../config/room_config.dart';
import 'gift_item_display.dart';

class GiftDisplay extends StatefulWidget {
  const GiftDisplay({Key? key}) : super(key: key);

  @override
  State<GiftDisplay> createState() => _GiftDisplayState();
}

class _GiftDisplayState extends State<GiftDisplay> with WidgetsBindingObserver {
  final List<DisplayGiftConfig> _data = [];

  ///正在播放的礼物
  final List<DisplayGiftConfig> _buffer = [];

  ///待播放的礼物
  AppLifecycleState _appLifecycleState = AppLifecycleState.resumed;
  final int _maxNum = 1; //并发限制
  StreamSubscription<Event>? _eventSub;

  @override
  void initState() {
    super.initState();
    _eventSub =
        eventCenter.subscribe(EventConstant.addNewGiftConfig).listen((event) {
      if (event.data is DisplayGiftConfig) {
        _updatePlayingGift(newConfig: event.data);
      }
    });
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    _eventSub?.cancel();
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    _appLifecycleState = state;
    if (_appLifecycleState == AppLifecycleState.resumed) {
      RLog.i("切换到了前台");
    } else if (state == AppLifecycleState.paused) {
      _buffer.clear();
      _data.clear();
      RLog.i("切换到了后台");
    }
  }

  _onComplete(DisplayGiftConfig config) {
    RLog.d('_onComplete:${config.iconUrl}');
    if (_data.contains(config)) {
      RLog.d('_onComplete:remove:${config.iconUrl}');
      _data.remove(config);
      _updatePlayingGift();
    }
  }

  bool _dataCanAddGift() {
    return _appLifecycleState == AppLifecycleState.resumed &&
        _data.length < _maxNum;
  }

  ///更新播放的礼物
  _updatePlayingGift({DisplayGiftConfig? newConfig}) {
    if (newConfig != null) {
      //增加新的礼物加到data或buff
      RLog.d('_updatePlayingGift:${newConfig.uid} key:${newConfig.key}');
      if (_dataCanAddGift()) {
        _dataAddConfig(newConfig);
      } else {
        _buffer.add(newConfig);
      }
    } else {
      //更新缓存礼物
      while (_dataCanAddGift() && _buffer.isNotEmpty) {
        _dataAddConfig(_buffer.removeAt(0));
      }
    }
    RLog.d(
        '_updatePlayingGift:_data:${_data.length}  _buffer:${_buffer.length}');
    if (mounted) {
      setState(() {});
    }
  }

  _dataAddConfig(DisplayGiftConfig config) {
    DisplayGiftConfig? result =
        _data.firstWhereOrNull((_) => _.key != null && _.key == config.key);
    if (result == null) {
      _data.add(config);
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_data.isEmpty) return const SizedBox.shrink();
    return IgnorePointer(
      child: Stack(
        children: _data.map((DisplayGiftConfig config) {
          return GiftItemDisplay(
            config,
            key: config.key,
            completeCallback: _onComplete,
          );
        }).toList(),
      ),
    );
  }
}
